﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;

namespace Mailias.UI.SendMailTool
{
    public partial class SendMail : Form
    {
        public SendMail()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            Cursor = Cursors.WaitCursor;

            int numberToSend = 1;
            int delayBetweenSends = 500;
            Int32.TryParse(SendMessageCount.Text, out numberToSend);
            Int32.TryParse(DelayAmount.Text.Replace(",", ""), out delayBetweenSends);

            SendProgress.Maximum = numberToSend * 2;
            SendProgress.Value = 0;
            SendProgress.Step = 1;
            SendProgress.Visible = true;

            for (int i = 0; i < numberToSend; i++)
            {
                SendProgress.PerformStep();
                string subject = MailiasSubject.Text;
                if (numberToSend > 1)
                {
                    subject += string.Format(" #{0} of {1}", i + 1, numberToSend);
                }
                SendMessage(ServerAddress.Text, ServerPort.Text, MailiasFrom.Text, MailiasTo.Text, subject, MailiasBody.Text);
                System.Threading.Thread.Sleep(delayBetweenSends);
                SendProgress.PerformStep();
            }
            button1.Enabled = true;
            SendProgress.Visible = false;
            Cursor = Cursors.Arrow;
        }

        private void SendMessage(string serverIP, string serverPort, string from, string to, string subject, string body)
        {
            MailMessage msg = new MailMessage();

            msg.To.Add(to);
            msg.Subject = subject;
            msg.From = new MailAddress(from);

            msg.IsBodyHtml = true;
            msg.Body = body;

            msg.BodyEncoding = Encoding.ASCII;

            int port = 8025;
            Int32.TryParse(serverPort, out port);

            using (SmtpClient smtp = new SmtpClient(serverIP, port))
            {
                try
                {
                    smtp.Send(msg);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

        }
    }

}
